from typing import List, Optional
from sqlalchemy.orm import Session
from app.models.device import Device
from app.schemas.device import DeviceCreate, DeviceUpdate
from uuid import UUID

class DeviceService:
    def get(self, db: Session, device_id: UUID) -> Optional[Device]:
        return db.query(Device).filter(Device.id == device_id).first()
    
    def get_multi(
        self, 
        db: Session, 
        *, 
        skip: int = 0, 
        limit: int = 100,
        filters: Optional[dict] = None
    ) -> List[Device]:
        query = db.query(Device)
        
        if filters:
            for key, value in filters.items():
                if hasattr(Device, key) and value is not None:
                    query = query.filter(getattr(Device, key) == value)
        
        return query.offset(skip).limit(limit).all()
    
    def create(self, db: Session, *, obj_in: DeviceCreate) -> Device:
        obj_data = obj_in.model_dump()
        db_obj = Device(**obj_data)
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj
    
    def update(self, db: Session, *, db_obj: Device, obj_in: DeviceUpdate) -> Device:
        obj_data = obj_in.model_dump(exclude_unset=True)
        for field, value in obj_data.items():
            if hasattr(db_obj, field):
                setattr(db_obj, field, value)
        
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj
    
    def remove(self, db: Session, *, id: UUID) -> Optional[Device]:
        obj = db.query(Device).get(id)
        if obj:
            db.delete(obj)
            db.commit()
        return obj